import { lazyInject } from 'legions-control-container';
import { LegionsProConditions,LegionsProDragger,LegionsProPageContainer,LegionsProTable } from 'legions-pro-design';
import { bind,observer } from 'legions/store-react';
import React from 'react';
import { QueryTemplateConfig } from '../../constants/template/query';
import ProjectStore from '../../stores/projectStore';
import classNames from 'classnames';
import { ContextStore } from '../../../common/components/contextStore/contextStore';
import { InstanceProTable } from 'legions-pro-design/es/LegionsProTable/interface';
import { ResponseVModelNameDataEntity } from '../../models/pageListEntity';
import { IOperationConfigCode } from '../../stores/projectTableProperty';
import { Row,Button } from 'antd';
import styles from '../../assets/css/table-list-page.modules.less'
import { TableListViewDomain } from '../../services/components/tableListViewDomain';
import { OPREATION_VIEW } from '../../constants/consts';
import { PropertyTableOperationFormFields } from '../../models/form/propertyFormModel';
interface IProps {
    store?: ProjectStore;
    onQueryPropertyClick: (value: { uid: string; name: string }) => void
}
@bind({ store: ProjectStore })
@observer
export class TableListContainer extends React.Component<IProps>{
    @lazyInject(QueryTemplateConfig)
    public queryTemplate!: QueryTemplateConfig;
    @lazyInject(TableListViewDomain)
    tableListViewDomain!: TableListViewDomain
    /** 拖拽搜索条件组件模型 */
    onDraggerAddConditions = (evt) => {
        const id = evt.clone.dataset.id as string;
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        QueryPropertyApp.insertQuerys(id,this.props.onQueryPropertyClick)
    }
    /** 搜索条件排序及删减 */
    onDraggerSortConditions = (items: string[],sort,evt) => {
        const dataId = evt.item.attributes['data-id']
        const moveToDraggerId = evt.to.attributes['dragger-id'];// 元素移动至容器Id
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        const computedQuery = QueryPropertyApp.queryComponentRef.viewModel.computedQuery;
        if (items.length < computedQuery.length && dataId && moveToDraggerId && moveToDraggerId.value === 'query') {
            const uuid = dataId.value;
            const index = computedQuery.findIndex((model) => model.containerProps.uuid === uuid);
            if (index > -1) {
                QueryPropertyApp.queryComponentRef.methods.removeQuery(uuid);
            }
        }
    }
    /** * 表格组件画布区域 */
    renderContentDragger() {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        return <LegionsProDragger
            style={{ width: '100%' }}
            options={{
                animation: 150,
                group: {
                    name: 'content',
                    pull: true,
                    put: true,
                },
            }}
            onChange={(items: string[]) => {
                console.log(items)
                TablePropertyApp.viewModel.contentDraggerList = items.length ? [items[0]] : [];
            }}
        >
            {TablePropertyApp.viewModel.contentDraggerList.length ? TablePropertyApp.viewModel.contentDraggerList.map((item) => {

                return <ContextStore content={(
                    <LegionsProTable<{},ResponseVModelNameDataEntity>
                        onReady={(instance: InstanceProTable) => {
                            instance.viewModel.isAdaptiveHeight = true;
                            instance.viewModel.bodyExternalContainer.set('btn',{ height: 32 });
                            instance.viewModel.bodyExternalContainer.set('other',{ height: 190 });
                            this.props.store.context.listPagePropertyApp.context.TablePropertyApp.tablePreviewRef = instance
                        }}
                        autoQuery={{
                            params: (pageIndex,pageSize) => {
                                return { pageSize,pageIndex }
                            },
                            token: '',
                            ApiUrl: '',
                            method: 'get',
                            transform: (value) => {
                                if (value && !value.isPending && value.value) {
                                    const { result = [],current,pageSize,total } = value.value;
                                    return {
                                        data: Array.isArray(result) && result.map((item,index) => {
                                            item['key'] = (index + 1) + (current - 1) * pageSize;
                                            return item;
                                        }),
                                        total: total,
                                    };
                                }
                                return {
                                    total: 0,
                                    data: [],
                                };
                            },
                            mappingEntity: (that,res) => {
                                that.result = res['data']
                            }
                        }}
                        size="middle"
                        scroll={{ y: 300,x: '100%' }}
                        loading={false}
                        total={0}
                        uniqueKey="id"
                        columns={TablePropertyApp.viewModel.tableColumns}
                        onPagingQuery={() => { }}
                    ></LegionsProTable>
                )}>< Row key={item} className={
                    classNames({
                        [styles['tableSelected']]: TablePropertyApp.viewModel.isEditByTable,
                    })}
                    // @ts-ignore
                    onClick={() => {
                        let isEditByTable = TablePropertyApp.viewModel.isEditByTable
                        TablePropertyApp.viewModel.isEditByTable = !isEditByTable
                        TablePropertyApp.tablePropertyDrawerModalRef.viewModel.visible = true;
                        TablePropertyApp.tablePropertyDrawerModalRef.viewModel.title = '设置表格属性'
                    }} >
                    </Row></ContextStore>
            }) : <Row
                // @ts-ignore
                onClick={() => {
                }}
                className={classNames({
                    [styles['tableUnSelected']]: true,
                })}
            ><h3>请拖入表格组件展示数据</h3></Row>}
        </LegionsProDragger>
    }
    /** 操作按钮画布区域 */
    renderOperationDragger() {
        const TbalePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        return <LegionsProDragger
            style={{ width: '100%' }}
            options={{
                animation: 150,
                group: {
                    name: 'operation',
                    pull: true,
                    put: true,
                },
            }}
            onChange={(items: string[],sort,evt) => {
                const DATAID = evt.item.attributes['data-id']
                const GROUP_NAME = evt.to.attributes['dragger-id'];
                const ViewCanvasApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
                if (items.length > 1 && items.length > ViewCanvasApp.viewModel.operationConfigCode.length) {
                    this.tableListViewDomain.onOperationAdd(DATAID.value)
                }
                else if (items.length > 1 && items.length === ViewCanvasApp.viewModel.operationConfigCode.length) {
                    const newQuery: IOperationConfigCode[] = [];
                    items.map((item) => { /** 操作按钮重新排序 */
                        const entity = ViewCanvasApp.viewModel.operationConfigCode.find((model) => model.id === item)
                        if (entity) {
                            newQuery.push(entity);
                        }
                    })
                    ViewCanvasApp.viewModel.operationConfigCode = newQuery;
                }
                else if (items.length < ViewCanvasApp.viewModel.operationConfigCode.length && DATAID && GROUP_NAME && GROUP_NAME.value === 'operation') {
                    const index = ViewCanvasApp.viewModel.operationConfigCode.findIndex((model) => model.id === DATAID.value)
                    if (index > -1) { /** 操作按钮删除 */
                        ViewCanvasApp.viewModel.dispatchAction(() => {
                            ViewCanvasApp.viewModel.operationConfigCode.splice(index,1);
                        })
                    }
                }
            }}
        >
            {TbalePropertyApp.viewModel.operationConfigCode.length ? TbalePropertyApp.viewModel.operationConfigCode.map((item,index) => {
                // @ts-ignore
                return <Button data-id={item.id} size="small" type={item.btnType} icon={item.btnIcon} onClick={this.onOperationClick.bind(this,item.type,item.id)}>{item.name}</Button>;
                /* </Dropdown> */
            }) : <Row className={classNames({
                [styles['operationUnSelected']]: true,
            })}
            ><h3>请拖入操作组件</h3></Row>}
        </LegionsProDragger>
    }
    onOperationClick = (type: string,id: string) => {
        const TablePropertyApp = this.props.store.context.listPagePropertyApp.context.TablePropertyApp;
        const defaultView = OPREATION_VIEW[type];
        const operationCurrView = TablePropertyApp.viewModel.operationConfigCode.find(item => item.id === id);
        TablePropertyApp.operationModalRef.viewModel.visible = true;
        TablePropertyApp.operationModalRef.viewModel.title = defaultView ? defaultView['name'] : '操作按钮';
        if (operationCurrView) {
            TablePropertyApp.viewModel.openOperationConfigId = id;
            const timeId = setTimeout(() => {
                //@ts-ignore
                const Model = PropertyTableOperationFormFields.dataToFormFields<PropertyTableOperationFormFields,IOperationConfigCode>(new PropertyTableOperationFormFields(),operationCurrView)
                this.props.store.formProperyOperattionRef.store.updateFormInputData(this.props.store.formProperyOperattionRef.uid,{ ...Model });
                ['paramsRenders','apiUrl','method'].map((item) => {
                    this.props.store.formProperyOperattionRef.methods.setFormStates(item,(value) => {
                        value.iFormProps.visible = Model.isNeedApi.value;
                    })
                })
                clearTimeout(timeId)
            },500);
        }
    }
    render() {
        const QueryPropertyApp = this.props.store.context.listPagePropertyApp.context.QueryPropertyApp;
        return <LegionsProPageContainer
            query={(
                <LegionsProConditions
                    isDragSort
                    draggerProps={{
                        options: {
                            onAdd: this.onDraggerAddConditions
                        },
                        onChange: this.onDraggerSortConditions
                    }}
                    query={[...this.queryTemplate.createSearchButton()]} onReady={(value) => {
                        QueryPropertyApp.queryComponentRef = value;
                    }}></LegionsProConditions>
            )}
            content={(
                this.renderContentDragger()
            )}
            operation={(this.renderOperationDragger())}
        ></LegionsProPageContainer>
    }
}
